import React, { useState } from 'react';
import { Button, Card, Badge, SettingsIcon, ServerIcon, FlashIcon, CodeIcon } from "@repo/ui";
import styles from './SettingsPage.module.css';

interface Setting {
  id: string;
  title: string;
  description: string;
  type: 'toggle' | 'select' | 'input' | 'range';
  value: any;
  options?: { label: string; value: any }[];
  min?: number;
  max?: number;
  step?: number;
  unit?: string;
}

const SettingsPage: React.FC = () => {
  const [settings, setSettings] = useState<Record<string, Setting>>({
    // 通用设置
    theme: {
      id: 'theme',
      title: '主题模式',
      description: '选择应用的外观主题',
      type: 'select',
      value: 'auto',
      options: [
        { label: '自动', value: 'auto' },
        { label: '明亮', value: 'light' },
        { label: '暗黑', value: 'dark' }
      ]
    },
    language: {
      id: 'language',
      title: '语言',
      description: '设置界面显示语言',
      type: 'select',
      value: 'zh-CN',
      options: [
        { label: '中文简体', value: 'zh-CN' },
        { label: 'English', value: 'en-US' },
        { label: '日本語', value: 'ja-JP' }
      ]
    },
    autoSave: {
      id: 'autoSave',
      title: '自动保存',
      description: '自动保存配置和工作进度',
      type: 'toggle',
      value: true
    },
    
    // 串口设置
    baudRate: {
      id: 'baudRate',
      title: '波特率',
      description: '串口通信波特率',
      type: 'select',
      value: 115200,
      options: [
        { label: '9600', value: 9600 },
        { label: '38400', value: 38400 },
        { label: '57600', value: 57600 },
        { label: '115200', value: 115200 },
        { label: '230400', value: 230400 },
        { label: '460800', value: 460800 },
        { label: '921600', value: 921600 }
      ]
    },
    dataBits: {
      id: 'dataBits',
      title: '数据位',
      description: '串口数据位设置',
      type: 'select',
      value: 8,
      options: [
        { label: '5', value: 5 },
        { label: '6', value: 6 },
        { label: '7', value: 7 },
        { label: '8', value: 8 }
      ]
    },
    stopBits: {
      id: 'stopBits',
      title: '停止位',
      description: '串口停止位设置',
      type: 'select',
      value: 1,
      options: [
        { label: '1', value: 1 },
        { label: '1.5', value: 1.5 },
        { label: '2', value: 2 }
      ]
    },
    parity: {
      id: 'parity',
      title: '校验位',
      description: '串口校验位设置',
      type: 'select',
      value: 'none',
      options: [
        { label: '无', value: 'none' },
        { label: '奇校验', value: 'odd' },
        { label: '偶校验', value: 'even' }
      ]
    },
    autoConnect: {
      id: 'autoConnect',
      title: '自动连接',
      description: '启动时自动连接设备',
      type: 'toggle',
      value: false
    },
    
    // 刷写设置
    flashTimeout: {
      id: 'flashTimeout',
      title: '刷写超时',
      description: '固件刷写超时时间',
      type: 'range',
      value: 30,
      min: 10,
      max: 120,
      step: 5,
      unit: '秒'
    },
    verifyFlash: {
      id: 'verifyFlash',
      title: '验证固件',
      description: '刷写后验证固件完整性',
      type: 'toggle',
      value: true
    },
    eraseFlash: {
      id: 'eraseFlash',
      title: '擦除Flash',
      description: '刷写前完全擦除Flash',
      type: 'toggle',
      value: false
    },
    
    // 高级设置
    logLevel: {
      id: 'logLevel',
      title: '日志级别',
      description: '控制台日志详细程度',
      type: 'select',
      value: 'info',
      options: [
        { label: '错误', value: 'error' },
        { label: '警告', value: 'warn' },
        { label: '信息', value: 'info' },
        { label: '调试', value: 'debug' }
      ]
    },
    maxLogLines: {
      id: 'maxLogLines',
      title: '最大日志行数',
      description: '终端显示的最大日志行数',
      type: 'range',
      value: 1000,
      min: 100,
      max: 5000,
      step: 100,
      unit: '行'
    },
    enableExperimentalFeatures: {
      id: 'enableExperimentalFeatures',
      title: '实验性功能',
      description: '启用实验性功能（可能不稳定）',
      type: 'toggle',
      value: false
    }
  });

  const [unsavedChanges, setUnsavedChanges] = useState(false);

  const settingCategories = [
    {
      id: 'general',
      title: '通用设置',
      icon: 'settings',
      settings: ['theme', 'language', 'autoSave']
    },
    {
      id: 'serial',
      title: '串口设置',
      icon: 'connection',
      settings: ['baudRate', 'dataBits', 'stopBits', 'parity', 'autoConnect']
    },
    {
      id: 'flash',
      title: '刷写设置',
      icon: 'flash',
      settings: ['flashTimeout', 'verifyFlash', 'eraseFlash']
    },
    {
      id: 'advanced',
      title: '高级设置',
      icon: 'advanced',
      settings: ['logLevel', 'maxLogLines', 'enableExperimentalFeatures']
    }
  ];

  const updateSetting = (settingId: string, value: any) => {
    setSettings(prev => ({
      ...prev,
      [settingId]: {
        ...prev[settingId],
        value
      }
    }));
    setUnsavedChanges(true);
  };

  const handleSave = () => {
    // 模拟保存设置
    console.log('保存设置:', settings);
    setUnsavedChanges(false);
    
    // 显示保存成功提示
    // TODO: 添加 toast 提示
  };

  const handleReset = () => {
    // 重置为默认设置
    window.location.reload();
  };

  const handleExport = () => {
    const settingsData = JSON.stringify(settings, null, 2);
    const blob = new Blob([settingsData], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'esp32-launchpad-settings.json';
    a.click();
    URL.revokeObjectURL(url);
  };

  const handleImport = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const importedSettings = JSON.parse(e.target?.result as string);
        setSettings(importedSettings);
        setUnsavedChanges(true);
      } catch (error) {
        console.error('导入设置失败:', error);
        // TODO: 显示错误提示
      }
    };
    reader.readAsText(file);
  };

  const renderSettingControl = (setting: Setting) => {
    switch (setting.type) {
      case 'toggle':
        return (
          <label className={styles.toggle}>
            <input
              type="checkbox"
              checked={setting.value}
              onChange={(e) => updateSetting(setting.id, e.target.checked)}
            />
            <span className={styles.toggleSlider}></span>
          </label>
        );
      
      case 'select':
        return (
          <select
            value={setting.value}
            onChange={(e) => updateSetting(setting.id, 
              setting.options?.find(opt => opt.value.toString() === e.target.value)?.value
            )}
            className={styles.select}
          >
            {setting.options?.map(option => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
        );
      
      case 'input':
        return (
          <input
            type="text"
            value={setting.value}
            onChange={(e) => updateSetting(setting.id, e.target.value)}
            className={styles.input}
          />
        );
      
      case 'range':
        return (
          <div className={styles.rangeControl}>
            <input
              type="range"
              min={setting.min}
              max={setting.max}
              step={setting.step}
              value={setting.value}
              onChange={(e) => updateSetting(setting.id, Number(e.target.value))}
              className={styles.range}
            />
            <span className={styles.rangeValue}>
              {setting.value}{setting.unit}
            </span>
          </div>
        );
      
      default:
        return null;
    }
  };

  const getIcon = (iconType: string) => {
    const iconProps = {
      width: "20",
      height: "20",
      fill: "none",
      stroke: "currentColor",
      viewBox: "0 0 24 24",
      strokeWidth: 2
    };

    switch (iconType) {
      case 'settings':
        return <SettingsIcon {...iconProps} />;
      case 'connection':
        return <ServerIcon {...iconProps} />;
      case 'flash':
        return <FlashIcon {...iconProps} />;
      case 'advanced':
        return <CodeIcon {...iconProps} />;
      default:
        return null;
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <div className={styles.titleSection}>
          <h1>设置</h1>
          <p>配置ESP32启动板的各项参数</p>
        </div>
        
        <div className={styles.actions}>
          {unsavedChanges && (
            <Badge variant="warning" size="sm">
              有未保存的更改
            </Badge>
          )}
          <Button variant="outline" size="sm" onClick={handleExport}>
            导出配置
          </Button>
          <Button variant="outline" size="sm" onClick={() => document.getElementById('import-input')?.click()}>
            导入配置
          </Button>
          <input
            id="import-input"
            type="file"
            accept=".json"
            onChange={handleImport}
            style={{ display: 'none' }}
          />
          <Button variant="outline" size="sm" onClick={handleReset}>
            重置默认
          </Button>
          <Button onClick={handleSave} disabled={!unsavedChanges}>
            保存设置
          </Button>
        </div>
      </div>

      <div className={styles.content}>
        {settingCategories.map(category => (
          <Card key={category.id} className={styles.categoryCard}>
            <div className={styles.categoryHeader}>
              <div className={styles.categoryIcon}>
                {getIcon(category.icon)}
              </div>
              <h2>{category.title}</h2>
            </div>
            
            <div className={styles.settingsList}>
              {category.settings.map(settingId => {
                const setting = settings[settingId];
                return (
                  <div key={settingId} className={styles.settingItem}>
                    <div className={styles.settingInfo}>
                      <div className={styles.settingTitle}>{setting.title}</div>
                      <div className={styles.settingDescription}>{setting.description}</div>
                    </div>
                    <div className={styles.settingControl}>
                      {renderSettingControl(setting)}
                    </div>
                  </div>
                );
              })}
            </div>
          </Card>
        ))}
      </div>
    </div>
  );
};

export default SettingsPage;
